package com.example.common.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.common.enums.ResponseCodeEnum;
import com.example.common.utils.ApiResult;
import com.example.common.utils.CacheUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.function.ServerResponse;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class MyInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(MyInterceptor.class);

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        System.out.println("拦截器preHandle方法");
        String servletPath = request.getServletPath();

        if(servletPath.startsWith("/login") || servletPath.startsWith("/websocket/")){
            return true;
        }
//        String token = request.getHeader("Authorization");
//        if(StringUtils.isBlank(token)){
//            response.setCharacterEncoding("UTF-8");
//            response.setContentType("application/json; charset=utf-8");
//            PrintWriter out = null ;
//            JSONObject res = new JSONObject();
//            res.put("code","9999");
//            res.put("message","登录信息失效，请重新登录");
//            out = response.getWriter();
//            out.append(res.toString());
//            return false;
//        }
//        Object obj = CacheUtils.get(token);
//        if(obj == null){
//            response.setCharacterEncoding("UTF-8");
//            response.setContentType("application/json; charset=utf-8");
//            PrintWriter out = null ;
//            JSONObject res = new JSONObject();
//            res.put("code","9999");
//            res.put("message","登录信息失效，请重新登录");
//            out = response.getWriter();
//            out.append(res.toString());
//            return false;
//        }
        return true;
    }

}